<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库配置管理 - AegisX</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .main-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            margin: 20px;
            padding: 30px;
        }
        
        .page-header {
            text-align: center;
            margin-bottom: 40px;
            padding-bottom: 20px;
            border-bottom: 2px solid #e9ecef;
        }
        
        .page-header h1 {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            font-weight: 700;
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .config-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }
        
        .config-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0, 0, 0, 0.15);
        }
        
        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0 !important;
            border: none;
            padding: 20px;
        }
        
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }
        
        .status-connected {
            background-color: #28a745;
        }
        
        .status-disconnected {
            background-color: #dc3545;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 10px;
            padding: 12px 24px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
        }
        
        .btn-outline-primary {
            border: 2px solid #667eea;
            color: #667eea;
            border-radius: 10px;
            padding: 12px 24px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-outline-primary:hover {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-color: #667eea;
            transform: translateY(-2px);
        }
        
        .form-control {
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 12px 16px;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .form-label {
            font-weight: 600;
            color: #495057;
            margin-bottom: 8px;
        }
        
        .btn-test {
            min-width: 100px;
        }
        
        .alert-custom {
            border-radius: 10px;
            border: none;
        }
        
        .loading-spinner {
            display: none;
        }
        
        /* 全屏优化样式 */
        body {
            margin: 0;
            padding: 0;
            background-color: #f8f9fa;
        }
        
        .container-fluid {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .container-fluid {
                padding-left: 1rem;
                padding-right: 1rem;
            }
            
            .card-body {
                padding: 1.5rem;
            }
            
            .btn-group .btn {
                font-size: 0.875rem;
                padding: 0.5rem 0.75rem;
            }
            
            .d-md-flex {
                flex-direction: column;
            }
            
            .d-md-flex .btn {
                margin-bottom: 0.5rem;
            }
        }
        
        @media (max-width: 576px) {
            .container-fluid {
                padding-left: 0.75rem;
                padding-right: 0.75rem;
            }
            
            .card-body {
                padding: 1rem;
            }
            
            .btn-group {
                flex-direction: column;
            }
            
            .btn-group .btn {
                border-radius: 0.375rem !important;
                margin-bottom: 0.25rem;
            }
        }
    </style>
</head>
<body>
    <div class="main-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <h1><i class="bi bi-database"></i> 数据库配置管理</h1>
            <p class="text-muted">管理和配置数据库连接设置</p>
        </div>
        
        <!-- 导航栏 -->
        <nav class="navbar navbar-expand-lg navbar-light bg-light rounded mb-4">
            <div class="container-fluid">
                <a class="navbar-brand" href="/">
                    <i class="bi bi-shield-check"></i> AegisX企业级智能插件平台
                </a>
                <div class="navbar-nav ms-auto">
                    <a class="nav-link" href="/">首页</a>
                    <a class="nav-link" href="/api-docs">API文档</a>
                    <a class="nav-link active" href="/database/config">数据库配置</a>
                    <a class="nav-link" href="/plugin-method">插件方法</a>
                </div>
            </div>
        </nav>

        <div class="row">
            <div class="col-12">

            <!-- 连接状态卡片 -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="card config-card">
                        <div class="card-body">
                            <div class="d-flex align-items-center justify-content-between">
                                <div>
                                    <h5 class="card-title mb-1">
                                        <i class="bi bi-activity me-2"></i>
                                        连接状态
                                    </h5>
                                    <p class="card-text mb-0">
                                        <span class="status-indicator" 
                                              th:class="${isConnected} ? 'status-indicator status-connected' : 'status-indicator status-disconnected'"></span>
                                        <span th:text="${isConnected} ? '已连接' : '未连接'" 
                                              th:class="${isConnected} ? 'text-success fw-bold' : 'text-danger fw-bold'">未连接</span>
                                    </p>
                                </div>
                                <button type="button" class="btn btn-outline-primary btn-test" onclick="testCurrentConnection()">
                                    <i class="bi bi-arrow-clockwise me-1"></i>
                                    测试连接
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 配置表单 -->
            <div class="row justify-content-center">
                <div class="col-xl-8 col-lg-10 col-md-12">
                    <div class="card config-card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="bi bi-gear-fill me-2"></i>
                                数据库连接配置
                            </h5>
                        </div>
                        <div class="card-body">
                            <!-- 消息提示区域 -->
                            <div id="messageArea"></div>

                            <form id="configForm">
                                <!-- 连接方式选择 -->
                                <div class="mb-4">
                                    <label class="form-label">
                                        <i class="bi bi-toggles me-1"></i>
                                        连接方式
                                    </label>
                                    <div class="btn-group w-100" role="group">
                                        <input type="radio" class="btn-check" name="configMode" id="urlMode" value="url" checked>
                                        <label class="btn btn-outline-primary" for="urlMode">
                                            <i class="bi bi-link-45deg me-1"></i>
                                            URL连接
                                        </label>
                                        <input type="radio" class="btn-check" name="configMode" id="separateMode" value="separate">
                                        <label class="btn btn-outline-primary" for="separateMode">
                                            <i class="bi bi-list-ul me-1"></i>
                                            分离配置
                                        </label>
                                    </div>
                                </div>

                                <!-- URL模式配置 -->
                                <div id="urlModeConfig">
                                    <div class="mb-3">
                                        <label for="dbUrl" class="form-label">
                                            <i class="bi bi-link me-1"></i>
                                            数据库URL
                                        </label>
                                        <input type="text" class="form-control" id="dbUrl" name="url" 
                                               th:value="${config.url}" 
                                               placeholder="jdbc:mysql://localhost:3306/database_name">
                                        <div class="form-text">
                                            示例: jdbc:mysql://localhost:3306/pf4j_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
                                        </div>
                                    </div>
                                </div>

                                <!-- 分离模式配置 -->
                                <div id="separateModeConfig" style="display: none;">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <div class="mb-3">
                                                <label for="dbHost" class="form-label">
                                                    <i class="bi bi-hdd-network me-1"></i>
                                                    主机地址
                                                </label>
                                                <input type="text" class="form-control" id="dbHost" name="host" 
                                                       th:value="${config.host}" 
                                                       placeholder="localhost">
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="mb-3">
                                                <label for="dbPort" class="form-label">
                                                    <i class="bi bi-ethernet me-1"></i>
                                                    端口
                                                </label>
                                                <input type="number" class="form-control" id="dbPort" name="port" 
                                                       th:value="${config.port}" 
                                                       placeholder="3306" min="1" max="65535">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="dbName" class="form-label">
                                            <i class="bi bi-database me-1"></i>
                                            数据库名
                                        </label>
                                        <input type="text" class="form-control" id="dbName" name="database" 
                                               th:value="${config.database}" 
                                               placeholder="pf4j_db">
                                    </div>
                                </div>

                                <!-- 认证信息 -->
                                <div class="mb-3">
                                    <label for="dbUsername" class="form-label">
                                        <i class="bi bi-person me-1"></i>
                                        用户名
                                    </label>
                                    <input type="text" class="form-control" id="dbUsername" name="username" 
                                           th:value="${config.username}" 
                                           placeholder="root" required>
                                </div>

                                <div class="mb-3">
                                    <label for="dbPassword" class="form-label">
                                        <i class="bi bi-key me-1"></i>
                                        密码
                                    </label>
                                    <div class="input-group">
                                        <input type="password" class="form-control" id="dbPassword" name="password" 
                                               placeholder="请输入数据库密码">
                                        <button class="btn btn-outline-secondary" type="button" onclick="togglePassword()">
                                            <i class="bi bi-eye" id="passwordToggleIcon"></i>
                                        </button>
                                    </div>
                                </div>

                                <!-- 高级配置 -->
                                <div class="mb-3">
                                    <label for="driverClassName" class="form-label">
                                        <i class="bi bi-cpu me-1"></i>
                                        驱动类名
                                    </label>
                                    <select class="form-select" id="driverClassName" name="driverClassName">
                                        <option value="com.mysql.cj.jdbc.Driver" 
                                                th:selected="${config.driverClassName == 'com.mysql.cj.jdbc.Driver'}">MySQL 8.0+</option>
                                        <option value="com.mysql.jdbc.Driver" 
                                                th:selected="${config.driverClassName == 'com.mysql.jdbc.Driver'}">MySQL 5.x</option>
                                    </select>
                                </div>

                                <!-- 操作按钮 -->
                                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                    <button type="button" class="btn btn-outline-secondary me-md-2" onclick="resetConfig()">
                                        <i class="bi bi-arrow-counterclockwise me-1"></i>
                                        重置配置
                                    </button>
                                    <button type="button" class="btn btn-outline-warning me-md-2" onclick="reloadDataSource()">
                                        <i class="bi bi-arrow-clockwise me-1"></i>
                                        重新加载
                                    </button>
                                    <button type="button" class="btn btn-outline-info me-md-2" onclick="testConnection()">
                                        <i class="bi bi-check-circle me-1"></i>
                                        <span class="loading-spinner spinner-border spinner-border-sm me-1" role="status"></span>
                                        测试连接
                                    </button>
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-check-lg me-1"></i>
                                        <span class="loading-spinner spinner-border spinner-border-sm me-1" role="status"></span>
                                        保存配置
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- 自定义JavaScript -->
    <script>
        // 切换配置模式
        document.querySelectorAll('input[name="configMode"]').forEach(radio => {
            radio.addEventListener('change', function() {
                const urlModeConfig = document.getElementById('urlModeConfig');
                const separateModeConfig = document.getElementById('separateModeConfig');
                
                if (this.value === 'url') {
                    urlModeConfig.style.display = 'block';
                    separateModeConfig.style.display = 'none';
                } else {
                    urlModeConfig.style.display = 'none';
                    separateModeConfig.style.display = 'block';
                }
            });
        });

        // 切换密码显示
        function togglePassword() {
            const passwordInput = document.getElementById('dbPassword');
            const toggleIcon = document.getElementById('passwordToggleIcon');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                toggleIcon.className = 'bi bi-eye-slash';
            } else {
                passwordInput.type = 'password';
                toggleIcon.className = 'bi bi-eye';
            }
        }

        // 显示消息
        function showMessage(message, type = 'info') {
            const messageArea = document.getElementById('messageArea');
            const alertClass = type === 'success' ? 'alert-success' : 
                              type === 'error' ? 'alert-danger' : 
                              type === 'warning' ? 'alert-warning' : 'alert-info';
            
            messageArea.innerHTML = `
                <div class="alert ${alertClass} alert-dismissible fade show alert-custom" role="alert">
                    <i class="bi bi-${type === 'success' ? 'check-circle' : 
                                     type === 'error' ? 'exclamation-triangle' : 
                                     type === 'warning' ? 'exclamation-triangle' : 'info-circle'} me-2"></i>
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
        }

        // 获取表单数据
        function getFormData() {
            const formData = new FormData(document.getElementById('configForm'));
            const data = {};
            
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            return data;
        }

        // 测试连接
        function testConnection() {
            const config = getFormData();
            const button = event.target;
            const spinner = button.querySelector('.loading-spinner');
            
            // 验证必填字段
            if (!validateConfig(config)) {
                return;
            }
            
            button.disabled = true;
            spinner.style.display = 'inline-block';
            showMessage('正在测试连接...', 'info');
            
            fetch('/database/api/test', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(config)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const duration = data.duration ? ` (${data.duration}ms)` : '';
                    showMessage(data.message + duration, 'success');
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('测试连接失败:', error);
                showMessage('测试连接失败: ' + error.message, 'error');
            })
            .finally(() => {
                button.disabled = false;
                spinner.style.display = 'none';
            });
        }
        
        // 验证配置
        function validateConfig(config) {
            if (config.configMode === 'url') {
                if (!config.url || config.url.trim() === '') {
                    showMessage('请输入数据库URL', 'error');
                    return false;
                }
            } else {
                if (!config.host || config.host.trim() === '') {
                    showMessage('请输入数据库主机地址', 'error');
                    return false;
                }
                if (!config.database || config.database.trim() === '') {
                    showMessage('请输入数据库名称', 'error');
                    return false;
                }
            }
            
            if (!config.username || config.username.trim() === '') {
                showMessage('请输入用户名', 'error');
                return false;
            }
            
            if (!config.password || config.password.trim() === '') {
                showMessage('请输入密码', 'error');
                return false;
            }
            
            return true;
        }
        
        // 重置配置
        function resetConfig() {
            if (!confirm('确定要重置为默认配置吗？这将清除当前所有配置。')) {
                return;
            }
            
            showMessage('正在重置配置...', 'info');
            
            fetch('/database/api/reset', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    // 重新加载配置
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('重置配置失败:', error);
                showMessage('重置配置失败: ' + error.message, 'error');
            });
        }
        
        // 重新加载数据源
        function reloadDataSource() {
            showMessage('正在重新加载数据源...', 'info');
            
            fetch('/database/api/reload', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    updateConnectionStatus();
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('重新加载数据源失败:', error);
                showMessage('重新加载数据源失败: ' + error.message, 'error');
            });
        }
        
        // 加载当前配置
        function loadCurrentConfig() {
            fetch('/database/api/config')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.config) {
                    populateForm(data.config);
                    updateConnectionStatus(data.isConnected);
                }
            })
            .catch(error => {
                console.error('加载配置失败:', error);
            });
        }
        
        // 填充表单
        function populateForm(config) {
            if (config.url) {
                document.getElementById('urlMode').checked = true;
                document.getElementById('dbUrl').value = config.url;
                document.getElementById('urlModeConfig').style.display = 'block';
                document.getElementById('separateModeConfig').style.display = 'none';
            } else {
                document.getElementById('separateMode').checked = true;
                document.getElementById('dbHost').value = config.host || '';
                document.getElementById('dbPort').value = config.port || 3306;
                document.getElementById('dbName').value = config.database || '';
                document.getElementById('urlModeConfig').style.display = 'none';
                document.getElementById('separateModeConfig').style.display = 'block';
            }
            
            document.getElementById('dbUsername').value = config.username || '';
            // 注意：出于安全考虑，不填充密码字段
            document.getElementById('driverClassName').value = config.driverClassName || 'com.mysql.cj.jdbc.Driver';
        }
        
        // 更新连接状态
        function updateConnectionStatus(isConnected) {
            if (isConnected === undefined) {
                // 如果没有传入状态，则从服务器获取
                fetch('/database/api/status')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateConnectionStatusUI(data.isConnected, data.configSummary);
                    }
                })
                .catch(error => {
                    console.error('获取连接状态失败:', error);
                });
            } else {
                updateConnectionStatusUI(isConnected);
            }
        }
        
        // 更新连接状态UI
        function updateConnectionStatusUI(isConnected, summary) {
            const statusIndicator = document.querySelector('.status-indicator');
            const statusText = statusIndicator.nextElementSibling;
            
            if (isConnected) {
                statusIndicator.className = 'status-indicator status-connected';
                statusText.textContent = '已连接';
                statusText.className = 'text-success fw-bold';
            } else {
                statusIndicator.className = 'status-indicator status-disconnected';
                statusText.textContent = '未连接';
                statusText.className = 'text-danger fw-bold';
            }
            
            if (summary) {
                statusText.textContent += ` (${summary})`;
            }
        }

        // 测试当前连接
        function testCurrentConnection() {
            const button = event.target;
            const spinner = button.querySelector('.loading-spinner');
            
            button.disabled = true;
            if (spinner) spinner.style.display = 'inline-block';
            
            fetch('/database/api/test', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    showMessage(result.message, 'success');
                    // 更新状态显示
                    location.reload();
                } else {
                    showMessage(result.message, 'error');
                }
            })
            .catch(error => {
                showMessage('测试连接失败: ' + error.message, 'error');
            })
            .finally(() => {
                button.disabled = false;
                if (spinner) spinner.style.display = 'none';
            });
        }

        // 保存配置
        function saveConfig() {
            const config = getFormData();
            
            // 验证必填字段
            if (!validateConfig(config)) {
                return;
            }
            
            showMessage('正在保存配置...', 'info');
            
            fetch('/database/api/config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(config)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage(data.message, 'success');
                    // 更新连接状态
                    updateConnectionStatus();
                    // 延迟刷新页面状态
                    setTimeout(() => {
                        loadCurrentConfig();
                    }, 1000);
                } else {
                    showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('保存配置失败:', error);
                showMessage('保存配置失败: ' + error.message, 'error');
            });
        }
        
        // 表单提交
        document.getElementById('configForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const data = getFormData();
            const submitButton = this.querySelector('button[type="submit"]');
            const spinner = submitButton.querySelector('.loading-spinner');
            
            // 验证必填字段
            if (!validateConfig(data)) {
                return;
            }
            
            submitButton.disabled = true;
            spinner.style.display = 'inline-block';
            showMessage('正在保存配置...', 'info');
            
            fetch('/database/api/config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    showMessage(result.message, 'success');
                    // 更新连接状态
                    updateConnectionStatus();
                    // 延迟刷新页面状态
                    setTimeout(() => {
                        loadCurrentConfig();
                    }, 1000);
                } else {
                    showMessage(result.message, 'error');
                }
            })
            .catch(error => {
                console.error('保存配置失败:', error);
                showMessage('保存配置失败: ' + error.message, 'error');
            })
            .finally(() => {
                submitButton.disabled = false;
                spinner.style.display = 'none';
            });
        });

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 根据当前配置设置表单模式
            const urlInput = document.getElementById('dbUrl');
            if (urlInput.value) {
                document.getElementById('urlMode').checked = true;
            } else {
                document.getElementById('separateMode').checked = true;
                document.getElementById('urlModeConfig').style.display = 'none';
                document.getElementById('separateModeConfig').style.display = 'block';
            }
        });
    </script>
</body>
</html>